# encoding:utf-8
'''2017-11-15 兼容独立运行'''

try:
    from pylibs.lpkg.jitencode import jit_encode
    from pylibs.lpkg.zip_file import zip_lpkg
except ImportError as identifier:
    from jitencode import jit_encode
    from zip_file import zip_lpkg

from optparse import OptionParser

def compile_script(pconfig, binpath=None):
    '''添加打包脚本'''
    frompath = pconfig["frompath"]
    tarfile = pconfig["tarfile"]

    if pconfig["isjit"]:
        if pconfig.has_key("bittype"):
            jit_encode(frompath, pconfig["bittype"])
        else:
            jit_encode(frompath)
    if pconfig["iszip"]:
        zip_lpkg(frompath, tarfile)


if __name__ == "__main__":
    print("======================================")
    print("=============AndroidPack==============")
    print("======================================")
    parser = OptionParser() 

    parser.add_option("-p", "--packpath", dest="packpath",
                      default=None, help="Input the lua-path u want to pack!")

    parser.add_option("-t", "--tarfile", dest="tarfile",
                      default=None, help="Input the lua-pack file u want to pack target")

    parser.add_option("-m", "--rmode", dest="rmode",
                      default=None, help="Input the module u want pack , the rmode could be |jitc32|jitc64|luac")

    (opts, args) = parser.parse_args()

    if (opts.packpath and opts.tarfile and opts.rmode):
        
        import os 
        import shutil
        import time
        import sys
        
        #chk temlate-dir first
        
        path_par = os.path.dirname(opts.packpath)
        path_tmp = os.path.join(path_par, "TEMPLATE_" + str(time.time()))
        path_ret = os.path.join(path_tmp, opts.packpath.split(os.sep)[-1])

        shutil.copytree(opts.packpath, path_ret)

        isjit = False if opts.rmode.find("jit") == -1 else True
        cfg = dict(
            isjit = isjit,
            frompath = opts.packpath,
            tarfile = opts.tarfile,
            iszip = True
        )
    
        
        if isjit:
            bittype = opts.rmode[-2:] + "bit"
            cfg["bittype"] = bittype
        print ("{} path is packing...".format(opts.packpath))
        compile_script(cfg)
        shutil.rmtree(path_tmp)
        print ("{} packed is done!".format(opts.tarfile))
    else:
        print ("Input all params first!")

